<template lang="html">
  <div ref="container" class="container" :style="`width:${container.width}px;height:${container.height}px;`">
    <div class="c-left" :style="`width:${container.left.width}px;height:100%;${showHandler.left?'':'border-right:unset;'}`">
      <span ref="leftToggleBtn" :class="`${showHandler.left?'el-icon-caret-left':'el-icon-caret-right'} s-h-icon`" @click="leftToggle()"></span>
      <div class="c-left-menu" v-if="showHandler.left">
        <el-form :model="searchForm" label-width="80px">
          <el-form-item label="车牌号：" prop="name">
            <el-input v-model="searchForm.vehicleNumber" placeholder="请输入名称" style="width:180px"/>
          </el-form-item>
          <el-form-item label="起始时间：" prop="remark">
            <el-date-picker style="width:180px"
              v-model="searchForm.startTime"
              value-format="yyyy-MM-dd HH:mm"
              type="datetime"
              placeholder="选择起始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：" prop="remark">
            <el-date-picker style="width:180px"
              value-format="yyyy-MM-dd HH:mm"
              v-model="searchForm.endTime"
              type="datetime"
              placeholder="选择结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="停车时长：">
            <el-input v-model="stopTimeLimit" style="width:120px">
              <template slot="append">分钟</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="searchGroup">
          <el-button icon="el-icon-search" @click="getMarkPath">查询</el-button>
        </div>
        <div class="playControlGroup" v-if="linePath.length>0">
          <div>
            <el-row>
              <el-col :span="8" style="width:80px;">回放进度：</el-col>
              <el-col :span="16" style="padding-top: 6px;">
                <el-progress :percentage="sliderVal" :show-text="false"></el-progress>
              </el-col>
             </el-row>
          </div>
          <div>
            <el-radio-group v-model="lineSpeed" @change="changeSpeed">
              <el-radio :label="100">×1</el-radio>
              <el-radio :label="500">×5</el-radio>
              <el-radio :label="1000">×10</el-radio>
              <el-radio :label="2000">×20</el-radio>
              <el-radio :label="5000">×50</el-radio>
            </el-radio-group>
          </div>
          <div>
            <el-button class="map-btn" icon="map-btn-start" @click="startAnimation" circle></el-button>
            <el-button class="map-btn" icon="map-btn-pause" @click="pauseAnimation" circle></el-button>
            <el-button class="map-btn" icon="map-btn-stop" @click="stopAnimation" circle></el-button>
          </div>
          <div>
            起点：{{startPoint.address}}
          </div>
          <div>
            终点：{{endPoint.address}}
          </div>
        </div>
      </div>
    </div>
    <div class="c-right" :style="`width:${container.main.width}px;height:100%;`">
      <div class="c-r-head" :style="`width:${container.main.width}px;height:40px;`"></div>
      <div class="c-r-main" :style="`width:100%;height:${container.main.height}px;`">
        <el-amap vid="myMap" :amap-manager="amapManager" :zoom="myMap.zoom" :center="myMap.center" :events="myMap.events" :plugin="myMap.plugin"></el-amap>
      </div>
      <div class="c-r-bottom" :style="`width:100%;height:${container.bottom.height}px;`">
        <span ref="bottomToggleBtn" :class="`${showHandler.bottom?'el-icon-caret-bottom':'el-icon-caret-top'} s-h-icon`" @click="bottomToggle()"></span>
        <div class="c-bottom-menu" v-if="showHandler.bottom">
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="分析报告" name="analyze">
              <el-row style="height:100%;">
                <el-col :span="8" style="height:100%;">
                  <SpeedChart ref="speedChart" width="100%" height="100%"></SpeedChart>
                </el-col>
                <el-col :span="8" style="height:100%;">
                  <SpeedChart ref="distanceChart" width="100%" height="100%"></SpeedChart>
                  <!--<SpeedChartJs width="100%" height="100%"></SpeedChartJs>-->
                </el-col>
                <el-col :span="8" style="height:100%;">
                  <div style="width: 300px;margin: auto;">
                    <div style="height: 50px;line-height: 50px;text-align:center;">轨迹/时间</div>
                    <div style="border: 1px solid #D6D6D6;background-color: #F4F6F9;padding: 10px; border-radius: 4px;">
                      <div style="height: 30px;line-height: 30px;">轨迹点：{{lineIndex===0?lineIndex:(lineIndex+1)}}/{{lineLength}}</div>
                      <div style="margin:10px 0;">
                        <el-progress :text-inside="true" :stroke-width="40"
                                        :percentage="lineLength?(lineIndex+1)*100/lineLength:0"
                                        :format="pointPercentFormat"></el-progress>
                      </div>
                      <div style="height: 30px;line-height: 30px;">上报时间：{{currentPoint.locationTime}}</div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="位置明细" name="position" style="overflow: auto;;width:100%;">
              <vxe-table ref="infoTable" :data="infoTable.data" :loading="loading" row-id="id" width="100%"
                         border resizable stripe highlight-current-row highlight-hover-row>
                <!--<vxe-table-column field="direction" title="车辆状态" width="100"/>-->
                <vxe-table-column field="locationTime" title="上报时间" width="160"/>
                <vxe-table-column field="mileage" title="GPS里程（公里）" width="160">
                  <template v-slot="{row}">
                    {{(row.mileage/1000).toFixed(2)}}
                  </template>
                </vxe-table-column>
                <vxe-table-column field="speed" title="速度（km/h）" width="120"/>
                <vxe-table-column field="address" title="位置描述" min-width="300" :formatter="addressFormatter"/>
              </vxe-table>
              <vxe-pager
                :loading="loading"
                :current-page.sync="infoTable.currentPage"
                :page-size.sync="infoTable.pageSize"
                :total="infoTable.total"
                :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
                @page-change="infoTablePageChange"
              />
            </el-tab-pane>
            <el-tab-pane label="停留点" name="stopPosition" style="overflow: auto;width:100%;">
              <vxe-table ref="stayTable" :data="stayTable.data" :loading="loading" row-id="id" width="100%"
                         border resizable stripe highlight-current-row highlight-hover-row>
                <vxe-table-column field="stopTime" title="停车时长" width="100">
                  <template v-slot="{row}">
                    {{(row.stopTime/60).toFixed(2)}}分钟
                  </template>
                </vxe-table-column>
                <vxe-table-column field="startTime" title="停车开始时间" width="160"/>
                <vxe-table-column field="endTime" title="停车结束时间" width="160"/>
                <vxe-table-column field="stopTime" title="停车位置" min-width="300" :formatter="addressFormatter"/>
              </vxe-table>
              <vxe-pager
                :loading="loading"
                :current-page.sync="stayTable.currentPage"
                :page-size.sync="stayTable.pageSize"
                :total="stayTable.total"
                :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
                @page-change="stayTablePageChange"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  // 时间格式控件
  import moment from 'moment'
  import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'
  import {setting,addLine,regeocoder} from './MyMap'
  import { vHisTrack } from "@/api/vehiclemap"
  import echarts from 'echarts'
  require('echarts/theme/macarons')
  import SpeedChart from './SpeedChart'
  import "@/assets/vehicle_map/icon.css";
  let amapManager = new AMapManager()
  export default {
    components: {
      SpeedChart,
    },
    data () {
      return {
        loading: false,
        showHandler:{
          left:true,
          bottom:true
        },
        container:{
          width:0,
          height:0,
          left:{
            width:300,
          },
          main:{
            height:0,
            width:0,
          },
          bottom:{
            height:240,
          }
        },
        amapManager,
        lazyAMapApiLoaderInstance,
        myMap:setting(this),
        markers:[],
        linePath:[],//路径坐标数组
        passedPath:[],//经过路径坐标数组
        linePoints:[],//路径点信息数组
        startPoint:{},//路径起始点信息
        endPoint:{},//路径结束点信息
        currentPoint:{},//路径回放，当前点位信息
        distance:0,//路径距离
        movedDistance:0,//移动的距离
        lineLength:0,//路径点数组长度
        lineIndex:0,//路径回放，当前点位序号
        lineSpeed:100,//路径回放，当前速度
        sliderVal:0,//路径长度移动百分比
        searchForm:{
          vehicleCode: "595d6d91ca694b58a9fd23e04df0b494",
          startTime: "",
          endTime: "",
          locationSource: 0
        },
        activeName: 'analyze',
        stayPoints:[],//停留点数组
        stopTimeLimit:10,//判定停留点时间（分钟）
        infoTable:{
          data:[],
          currentPage: 1,
          pageSize: 10,
          sortField: '',
          sortType: '',
          total: 0
        },
        stayTable:{
          data:[],
          currentPage: 1,
          pageSize: 10,
          sortField: '',
          sortType: '',
          total: 0
        },
      }
    },
    created() {
      this.searchForm.vehicleNumber = this.$route.query.vehicleNumber;
      this.searchForm.vehicleCode = this.$route.query.vehicleCode;
      let now = new Date();
      this.searchForm.startTime = moment(now).subtract(1,'day').format('YYYY-MM-DD HH:mm');
      this.searchForm.endTime = moment(now).format('YYYY-MM-DD HH:mm');;
    },
    mounted(){
      this.selfAdaption();
      let that = this;
      window.onresize = function(){
        that.selfAdaption();
      }
      this.$nextTick(() => {
        this.$refs.speedChart.initChart('行驶速度','{value}km/h',0,180);
        this.$refs.distanceChart.initChart('轨迹里程','{value}km',0,0);
      });
    },
    methods: {
      // 分页handle
      infoTablePageChange({ currentPage, pageSize }) {
        this.infoTable.currentPage = currentPage;
        this.infoTable.pageSize = pageSize;
        if(currentPage*pageSize>this.linePoints.length){
          this.infoTable.data = this.linePoints.slice((currentPage-1)*pageSize);
        }else{
          this.infoTable.data = this.linePoints.slice((currentPage-1)*pageSize,currentPage*pageSize);
        }
      },stayTablePageChange({ currentPage, pageSize }) {
        this.stayTable.currentPage = currentPage;
        this.stayTable.pageSize = pageSize;
        if(currentPage*pageSize>this.stayPoints.length){
          this.stayTable.data = this.stayPoints.slice((currentPage-1)*pageSize);
        }else{
          this.stayTable.data = this.stayPoints.slice((currentPage-1)*pageSize,currentPage*pageSize);
        }
      },
      selfAdaption(){
        this.container.width = document.documentElement.clientWidth;
        this.container.height = document.documentElement.clientHeight;
        this.container.main.width = this.container.width-this.container.left.width;
        this.container.main.height = this.container.height-this.container.bottom.height;
      },
      leftToggle(){
        this.showHandler.left = !this.showHandler.left;
        if(this.showHandler.left){
          this.container.left.width = 300;
        }else{
          this.container.left.width = 0;
        }
        this.selfAdaption();
      },
      bottomToggle(){
        this.showHandler.bottom = !this.showHandler.bottom;
        if(this.showHandler.bottom){
          this.container.bottom.height = 240;
        }else{
          this.container.bottom.height = 0;
        }
        this.selfAdaption();
      },changeSpeed(){
        this.firstPath.setSpeed(this.lineSpeed);
      },startAnimation() {
        if(this.firstPath._naviStatus==='pause'){
          this.firstPath.resume()
        }else if(this.firstPath._naviStatus==='stop'){
          this.$set(this,'lineIndex',0);
          this.$set(this,'sliderVal',0);
          this.firstPath.start();
        }
      },pauseAnimation() {
        this.firstPath.pause();
      },stopAnimation() {
        this.firstPath.stop();
      },initChart() {
        this.chart = echarts.init(this.$el, 'macarons');
        this.setOptions(this.chartData);
      },getMarkPath(){
        if(this.searchForm.startTime&&this.searchForm.endTime){
          let start = new Date(this.searchForm.startTime);
          let end = new Date(this.searchForm.endTime);
          if(start>=end){
            this.$message({ message: '开始时间必须小于结束时间！', type: 'error' });
            return;
          }else if(end-start>86400000){
            this.$message({ message: '所选择时间范围不能大于一天！', type: 'error' });
            return;
          }
          if(this.firstPath){//地图路径重查时，重置信息。
            this.firstPath.stop();
            this.$refs.speedChart.change(0,0,180);
            this.$refs.distanceChart.change(0,0,0);
            this.sliderVal = 0;
            this.lineIndex = 0;
          }
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          vHisTrack(this.searchForm).then(response => {
            this.loadLine(response.data);
            loading.close();
          });
        }else{
          this.$message({ message: '请选择时间范围！', type: 'error' });
        }
      },
      loadStopPoints(){
        let len = this.stayPoints.length;
        if(len>0){
          for(let i=0;i<len;i++){
            this.markers.push(new AMap.Marker({
              map:this.map,
              position: [this.stayPoints[i].longitude,this.stayPoints[i].latitude],
              icon: new AMap.Icon({
                size: new AMap.Size(32, 32),
                image: require('@/assets/vehicle_map/image/line_stop.png'),
                imageSize: new AMap.Size(32, 32)
              }),
              offset: new AMap.Pixel(-16, -32),
            }));
          }
        }
      },
      loadLine(list){
        if(this.markers.length>0){
          this.map.remove(this.markers);
          this.markers.length = 0;
        }
        if(list&&list.length>0){
          this.lineLength = list.length;
          this.linePoints = list;
          let linePath = [];
          let lastMileage = 0;
          let lastLocationTime = 0;
          let lastPoint = {};
          let stayPoints = [];//停车点记录
          for(let i in list){
            linePath.push([list[i].longitude, list[i].latitude]);
            if(list[i].locationTime){
              let locationTime = new Date(list[i].locationTime.replace(/-/g,"/"));
              if(lastLocationTime===0){
                lastPoint = list[i];
                lastLocationTime = locationTime;
                lastMileage = list[i].mileage;
              }else if(list[i].mileage>lastMileage){
                let stopTime = (locationTime-lastLocationTime)/1000;
                if(stopTime>(60*this.stopTimeLimit)){
                  stayPoints.push({longitude:lastPoint.longitude,latitude:lastPoint.latitude,startTime:lastPoint.locationTime,endTime:list[i].locationTime,stopTime:stopTime});
                }
                lastPoint = list[i];
                lastLocationTime = locationTime;
                lastMileage = list[i].mileage;
              }
            }
          }
          this.stayPoints = stayPoints;
          this.initTable();
          this.linePath = linePath;
          this.distance = Math.round(AMap.GeometryUtil.distanceOfLine(linePath)/1000);

          regeocoder(this,list[0],(val)=>{
            this.$set(list[0],'address',val);
          });
          regeocoder(this,list[this.lineLength-1],(val)=>{
            this.$set(list[this.lineLength-1],'address',val);
          });
          this.startPoint = list[0];
          this.endPoint = list[this.lineLength-1];

          this.$refs.distanceChart.change(0,0,this.distance);
          addLine(this,linePath);
          this.loadStopPoints();
        }else{
          this.$message({ message: '该时间范围内未查询到轨迹！', type: 'error' });
        }
      },changePoint(idx){
        this.lineIndex = idx;
        this.currentPoint = this.linePoints[idx];
        this.movedDistance = Math.round(this.firstPath.getMovedDistance()/1000);
        this.$refs.speedChart.change(this.currentPoint.speed,0,180);
        this.$refs.distanceChart.change(this.movedDistance,0,this.distance);
      },pointPercentFormat(){
        if(this.lineIndex===0){
          return `${this.lineIndex}/${this.lineLength}`;
        }else{
          return `${this.lineIndex+1}/${this.lineLength}`;
        }
      },initTable(){
        if(this.infoTable.pageSize>this.linePoints.length){
          this.infoTable.data = this.linePoints.slice((this.infoTable.currentPage-1)*this.infoTable.pageSize);
        }else{
          this.infoTable.data = this.linePoints.slice((this.infoTable.currentPage-1)*this.infoTable.pageSize,this.infoTable.currentPage*this.infoTable.pageSize);
        }
        this.infoTable.total = this.linePoints.length;

        if(this.stayTable.pageSize>this.stayPoints.length){
          this.stayTable.data = this.stayPoints.slice((this.stayTable.currentPage-1)*this.stayTable.pageSize);
        }else{
          this.stayTable.data = this.stayPoints.slice((this.stayTable.currentPage-1)*this.stayTable.pageSize,this.stayTable.currentPage*this.stayTable.pageSize);
        }
        this.stayTable.total = this.stayPoints.length;
      },handleTabClick(tab,e){
        /*if('position'==tab.name){

        }*/
      },addressFormatter({ row }){
        if(!row.address){
          regeocoder(this,row,(val)=>{
            this.$set(row,'address',val);
          });
        }
        return row.address;
      }
    }
  }
</script>
<style lang="scss" type="text/scss">
  .container{
    width: 100%;
    height: 100%;
    overflow: hidden;
    .s-h-icon{
      position: absolute;
      border: 1px solid #c9cbc6;
      background-color: #f3f7f8;
      cursor:pointer;
      z-index: 1;
    }
    .c-left{
      float: left;
      width: 200px;
      height: 100%;
      border-right: 1px solid #C9CBC6;
      background-color: #F3F7F8;
      position: relative;
      .s-h-icon{
        right: -13px;
        top: 50%;
        margin-top: -16px;
        border-left: unset;
        height: 48px;
        padding: 16px 0px;
        border-radius: 0 10px 10px 0;
      }
      .c-left-menu{
        .el-form{
          padding:10px;
          .el-form-item{
            margin-bottom: 10px;
            .el-form-item__label {
              padding: 0;
            }
          }
        }
        .searchGroup{
          padding:10px;
        }
        .playControlGroup{
          padding:10px;
          border-top: 1px solid #c9cbc6;
          border-bottom: 1px solid #c9cbc6;
          font-weight: bold;font-size: 14px;color: #606266;
          >div{
            padding:0 0 10px 0;
            .el-radio-group{
              .el-radio{
                margin-right: 15px;
                .el-radio__label{
                  padding-left: 2px;
                }
              }
            }
            .el-button--medium.is-circle{
              padding:0px;
              >i{
                font-size: 30px;
              }
            }
          }
        }
      }
      .el-icon-caret-left:before {
        margin: 0 -1px 0 -3px;
        display: block;
      }
      .el-icon-caret-right:before {
        margin: 0 -1px 0 -3px;
        display: block;
      }
    }
    .c-right{
      float: right;
      height: 100%;
      .c-r-head{
        height: 60px;
        width: 100%;
        background-color: rgba(0,0,0,0.4);
        position: absolute;
        z-index: 0;
      }
      .c-r-main{
        width: 100%;
        background-color: #0bb2d4;
      }
      .c-r-bottom{
        width: 100%;
        height: 200px;
        position: relative;
        .s-h-icon{
          right: 50%;
          top: -12px;
          border-bottom: unset;
          width: 48px;
          padding: 0 16px;
          border-radius: 10px 10px 0 0;
        }
        .el-icon-caret-top:before {
          margin: -2px 0 -2px 0;
          display: block;
        }
        .el-icon-caret-bottom:before {
          margin: -2px 0 -2px 0;
          display: block;
        }
        .c-bottom-menu{
          border-top: 1px solid #C9CBC6;
          background-color: #F3F7F8;
          height: 100%;
          width: 100%;
          .el-tabs{
            height:100%;
            .el-tabs__header{
              margin-bottom: 0;
            }
            .el-tabs__content{
              height:200px;
              .el-tab-pane{
                height: 200px;
              }
            }
          }
        }
      }
    }
    .amap-logo{
      opacity:0;
    }
    .amap-copyright{
      opacity:0;
    }
  }
</style>
